package com.mjfeed.controller.shop;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mjfeed.controller.BaseController;
import com.mjfeed.entity.Cart;
import com.mjfeed.entity.CartItem;
import com.mjfeed.entity.Member;
import com.mjfeed.entity.Product;
import com.mjfeed.service.CartItemService;
import com.mjfeed.service.CartService;
import com.mjfeed.service.MemberService;
import com.mjfeed.service.ProductCategoryService;
import com.mjfeed.service.ProductService;
import com.mjfeed.util.Md5Util;
import com.mjfeed.util.WebUtils;

/**
 * @description 购物车
 * @author zhaominglei
 * @date 2014年10月7日
 */
@Controller("shopCartController")
@RequestMapping("/cart")
public class CartController extends BaseController {
	
	@Resource(name="memberService")
	private MemberService memberService;
	@Resource(name="productService")
	private ProductService productService;
	@Resource(name="cartService")
	private CartService cartService;
	@Resource(name="cartItemService")
	private CartItemService cartItemService;
	@Resource(name="productCategoryService")
	private ProductCategoryService productCategoryService;
	
	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> add(Long id, Integer quantity, HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> data = new HashMap<String, Object>();
		if (id == null || quantity == null || quantity < 1) {
			data.put("success", "false");
			data.put("message", "param error");
			return data;
		}
		Product product = productService.getById(Product.class, id);
		if (product == null ) {
			data.put("success", "false");
			data.put("message", "product not exists");
			return data;
		}
		if (!product.getIsMarketable()) {
			data.put("success", "false");
			data.put("message", "product not marketable");
			return data;
		}
		if (product.getIsGift()) {
			data.put("success", "false");
			data.put("message", "product is gift");
			return data;
		}
		Cart cart = cartService.getCurrent();
		Member member = memberService.getCurrent();
		
		if (cart == null) {
			cart = new Cart();
			cart.setKey(Md5Util.encrypt(RandomStringUtils.randomAlphabetic(30)));
			cart.setMember(member);
			cartService.save(cart);
		} else {
			cart.setMember(member);
			cartService.merge(member, cart);
		}
		if (cart.contains(product)) {
			CartItem cartItem = cart.getCartItem(product);
			if (product.getStock() != null && cartItem.getQuantity() + quantity > product.getStock()) {
				data.put("success", "false");
				data.put("message", "product lowstock");
				return data;
			}
			cartItem.add(quantity);
			cartItemService.update(cartItem);
		} else {
			if (product.getStock() != null && quantity > product.getStock()) {
				data.put("success", "false");
				data.put("message", "product lowstock");
				return data;
			}
			CartItem cartItem = new CartItem();
			cartItem.setQuantity(quantity);
			cartItem.setProduct(product);
			cartItem.setCart(cart);
			cartItemService.save(cartItem);
			cart.getCartItems().add(cartItem);
			cartService.update(cart);
		}
		if (member == null) {
			WebUtils.addCookie(request, response, Cart.ID_COOKIE_NAME, cart.getId().toString(), Cart.TIMEOUT);
			WebUtils.addCookie(request, response, Cart.KEY_COOKIE_NAME, cart.getKey(), Cart.TIMEOUT);
		} 
		data.put("success", "true");
		data.put("message", "success");
		data.put("quantity", cart.getQuantity());
		data.put("price", cart.getPrice());
		return data;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		request.setAttribute("cart", cartService.getCurrent());
		request.setAttribute("productCategoryTree", productCategoryService.findTree());
		return "shop/cart/list";
	}
	
	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> edit(Long id, Integer quantity) {
		Map<String, Object> data = new HashMap<String, Object>();
		if (quantity == null || quantity < 1) {
			data.put("success", "false");
			data.put("message", "quantity lt 1");
			return data;
		}
		Cart cart = cartService.getCurrent();
		if (cart == null || cart.isEmpty()) {
			data.put("success", "false");
			data.put("message", "cart isempty");
			return data;
		}
		CartItem cartItem = cartItemService.getById(CartItem.class, id);
		Set<CartItem> cartItems = cart.getCartItems();
		if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
			data.put("success", "false");
			data.put("message", "cartItem not exists");
			return data;
		}
		if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
			data.put("success", "false");
			data.put("message", "cartItem gt maxquantity");
			return data;
		}
		Product product = cartItem.getProduct();
		if (product.getStock() != null && quantity > product.getStock()) {
			data.put("success", "false");
			data.put("message", "product lowstock");
			return data;
		}
		cartItem.setQuantity(quantity);
		cartItemService.update(cartItem);

		data.put("success", "true");
		data.put("message", "success");
		data.put("subtotal", cartItem.getSubtotal());
		data.put("price", cart.getPrice());
		data.put("quantity", cart.getQuantity());
		data.put("isLowStock", cartItem.getIsLowStock());
		return data;
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> delete(Long id) {
		Map<String, Object> data = new HashMap<String, Object>();
		Cart cart = cartService.getCurrent();
		if (cart == null || cart.isEmpty()) {
			data.put("success", "false");
			data.put("message", "cart isempty");
			return data;
		}
		CartItem cartItem = cartItemService.getById(CartItem.class, id);
		Set<CartItem> cartItems = cart.getCartItems();
		if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
			data.put("success", "false");
			data.put("message", "cartItem not exists");
			return data;
		}
		cartItems.remove(cartItem);
		cartItemService.delete(cartItem);
		cartService.update(cart);
		
		data.put("success", "true");
		data.put("quantity", cart.getQuantity());
		data.put("price", cart.getPrice());
		data.put("isLowStock", cart.getIsLowStock());
		return data;
	}
	
	/**
	 * 清空
	 */
	@RequestMapping(value = "/clear", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> clear() {
		Map<String, Object> data = new HashMap<String, Object>();
		Cart cart = cartService.getCurrent();
		cartService.delete(cart);
		data.put("success", "true");
		data.put("message", "success");
		return data;
	}
	
	/**
	 * 获取购物车信息
	 */
	@RequestMapping(value = "/getCart", method = RequestMethod.GET)
	public @ResponseBody Map<String, Object> getCart(HttpServletRequest request, HttpServletResponse response){
		Map<String, Object> data = new HashMap<String, Object>();
		Cart cart = cartService.getCurrent();
		if (cart != null) {
			data.put("quantity", cart.getQuantity());
			data.put("price", cart.getPrice());
		} else {
			data.put("quantity", 0);
			data.put("price", 0);
		}
		data.put("success", "true");
		data.put("message", "success");
		return data;
	}
}
